﻿using System.Data.Entity;
using KPIS.GERP.Models;
using KPIS.GERP.Models.BGM;
using KPIS.GERP.Models.Class;
using System;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.ICM;
using Resources;
//Adding
using System.Collections.Generic;
using System.Drawing;
using KPIS.GERP.Models.HRM;
using Novacode;
using System.Data;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class PurchaseController : Controller
    {
	    private string[] _basicIncludeSubclass = new[]
		    {
				"Priority", "DurationType", "DurationCount" , "YearType", "MasPurchaseType", "MasPurchaseMethod"
				//"Committees", "Files", "PrePurchaseRequestItems"
				//, "RequestEmployee", "Progress"
		    };

        public ActionResult Index()
        {
            var service = new PurchaseRequestService.PurchaseRequestServiceClient();
            ViewBag.SuccessMessage = TempData["SuccessMessage"];
            ViewBag.ErrorMessage = TempData["ErrorMessage"];
            return View(service.Select(new Models.ICM.PurchaseRequest { RecordStatus = "!D" }, _basicIncludeSubclass).OrderBy(m => m.Code).ToList());
        }

        public ActionResult Details(int id, bool? nolayout = false, bool? ViewOnly = false)
		{
            ViewBag.EmptyLayout = nolayout ?? false;

            var service = new PurchaseRequestService.PurchaseRequestServiceClient();
            var serviceItem = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
            var servicePprItem = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var serviceCommittee = new CommitteeService.CommitteeServiceClient();
            var model = service.Select(new PurchaseRequest { PrId = id }, _basicIncludeSubclass).FirstOrDefault();
            ViewBag.EmptyLayout = nolayout;
            ViewBag.ViewOnly = ViewOnly;

            // Remark: Use this way to get comittee ( pprid of first requestitem )
            var prItemId = serviceItem.Select(new PurchaseRequestItem { PrId = id }, null).FirstOrDefault().PrItemId;
            var ppr = servicePprItem.Select(new PrePurchaseRequestItem { PrItemId = prItemId }, null).FirstOrDefault();
            ViewBag.PprId = ppr != null ? ppr.PprId : (int?)null;

            return View(model);
		}

        //public ActionResult Create()
        //{
        //    return View();
        //}

        //[HttpPost, ValidateAntiForgeryToken]
        //public ActionResult Create(PrePurchaseRequest model, FormCollection collection)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        try
        //        {
        //            var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
        //            model.RequestEmpId = 1;// new UserService.UserServiceClient().GetEmployeeByUser(Class.GimsMembership.CurrentEmpId).EmpId;
        //            var id = service.Insert(model, Class.GimsMembership.CurrentEmpId);
        //            return RedirectToAction("Details", new { id });
        //        }
        //        catch (Exception ex)
        //        {
        //            throw ex;
        //        }
        //    }
        //    return View(model);
        //}

		public ActionResult Edit(int id)
        {
            var service = new PurchaseRequestService.PurchaseRequestServiceClient();
			var model = service.Select(new PurchaseRequest { PrId = id }, _basicIncludeSubclass).FirstOrDefault();
            return View(model);
        }

        [HttpPost]
		public ActionResult Edit(int id, PurchaseRequest model)
        {
            try
            {
				if (ModelState.IsValid && model.PcMethodId.HasValue)
				{
					var service = new PurchaseRequestService.PurchaseRequestServiceClient();
					service.Update(model, Class.GimsMembership.CurrentEmpId);

					return RedirectToAction("Details", new { id });
                }
			}
			catch (Exception ex)
            {
				throw ex;
            }

            ModelState.AddModelError("", Models.Class.ValidateText.RequiredField);
			return View(model);
        }

		public ActionResult Delete(int id)
		{
			try
			{
				var service = new PurchaseRequestService.PurchaseRequestServiceClient();
				service.Delete(id, Class.GimsMembership.CurrentEmpId);
				service.Close(); 
		        TempData["SuccessMessage"] = "ลบข้อมูลไปทั้งหมด 1 รายการ";
		        return RedirectToAction("Index");
			}
			catch (Exception ex)
			{
		        string m = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : "");
		        TempData["ErrorMessage"] = m;
		        return RedirectToAction("Index");
			}
		}

		[HttpPost, ValidateAntiForgeryToken]
		public ActionResult DeleteAll(int[] deleteIds)
		{
		    if (deleteIds == null)
		    {
		        string m = "โปรดเลือกข้อความ";
		        TempData["SuccessMessage"] = m;
		        return RedirectToAction("Index");
		    }

		    try
		    {
		        var service = new PurchaseRequestService.PurchaseRequestServiceClient();
		        foreach (int delete in deleteIds)
		        {
		            service.Delete(delete, Class.GimsMembership.CurrentEmpId);
		        }

		        string message = string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0"));
		        // ModelState.AddModelError(ErrorLocalization.Error, message); // <-- For what ??

		        string m = message;
		        TempData["SuccessMessage"] = m;
		        return RedirectToAction("Index");
		    }
		    catch (Exception ex)
		    {
		        ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
		        GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
		        string m = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : "");
		        TempData["ErrorMessage"] = m;
		        return RedirectToAction("Index");
		    }
		}

        public ActionResult GetPurchaseMethod(int id)
        {
            var service = new IcmMasterService.IcmMasterServiceClient();
            var result = service.SelectListPurchaseMethod(new Models.ICM.MasPurchaseMethod() { PcTypeId = id
                , RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus }, true);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        private class PrItemReport
        {

            public string BidderName { get; set; }
            public string ItemName { get; set; }
            public int PrItemId { get; set; }
            public int Qty { get; set; }
            public decimal Price { get; set; }
            public decimal VatAmount { get; set; }
            public decimal DiscountTotal { get; set; }
            public decimal NetAmount { get; set; }
        }

        public void ReportPurchaseRequest(int? id)
        {
            var service = new PurchaseRequestService.PurchaseRequestServiceClient();

            var model = service.Select(new PurchaseRequest { PrId = id.Value }, _basicIncludeSubclass).FirstOrDefault();

            Dictionary<string, string> fields = new Dictionary<string, string>();
            MailMerge mailMerge = new MailMerge();

            fields.Add("PRCode", model.Code);
            string typeName = model.MasPurchaseType.PcTypeName;
            if (typeName == "จ้าง")
            {
                typeName = "จ้างเหมาบริการ";
            } 
            fields.Add("TypeName", typeName);
            fields.Add("MethodName", model.MasPurchaseMethod.Name);
            fields.Add("PrName", model.Name);
            fields.Add("PurchaseDate", Convert.ToDateTime(model.PurchaseDate).ToLongDateString());
            fields.Add("CreateDate", Convert.ToDateTime(model.CreatedWhen).ToLongDateString());
            fields.Add("Reason",model.Reason);
            fields.Add("RequireDuration", (model.RequireDuration == null ? "0":model.RequireDuration.Value.ToString()));
            fields.Add("RequireDate", GetRequireDate(model));//model.RequireDate == null ? "" : Convert.ToDateTime(model.RequireDate).ToLongDateString());

            var serviceItem = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();

            var db = new GERPContext(true);
            var prItems = db.PurchaseRequestItems.Where(o => o.PrId == id && o.RecordStatus != "D")
                .Include("MasResourceItem")
                .Select(o => new PrItemReport
                {
                    ItemName = o.HaveItem == true ? o.MasResourceItem.Name : o.Descr,
                    PrItemId = o.PrItemId,
                    Qty = o.Qty ?? 0,
                    Price = (decimal)0.0,
                    VatAmount = (decimal)0.0,
                    DiscountTotal = (decimal)0.0,
                    NetAmount = (decimal) 0.0
                }).ToList();

            var prItemIds = prItems.Select(o => o.PrItemId).ToArray();
            var selectedBidderQuos = db.BidderQuotations.Include("Bidder.MasContact")
                .Where(o =>
                    o.Selected == "1" &&
                    prItemIds.Contains(o.PrItemId ?? 0)).ToList();
            decimal TotalPrice = 0, Vat = 0, NetAmount = 0, DiscountTotal = 0; 
            foreach (var prItem in prItems)
            {
                var selectedBidderQuo = selectedBidderQuos.FirstOrDefault(o => o.PrItemId == prItem.PrItemId);
                if (selectedBidderQuo != null && selectedBidderQuo.Qty.HasValue)
                {
                    prItem.BidderName = selectedBidderQuo.Bidder != null &&
                                        selectedBidderQuo.Bidder.MasContact != null
                        ? selectedBidderQuo.Bidder.MasContact.NameTh
                        : "(ยังไม่มีผู้ขาย)";
                    prItem.Price = selectedBidderQuo.Price ?? 0;
                    prItem.VatAmount = selectedBidderQuo.VatAmount ?? 0;
                    prItem.DiscountTotal = (
                        (selectedBidderQuo.ExcludeVatAmount ?? 0) +
                        (selectedBidderQuo.VatAmount ?? 0)
                        )
                                           - (selectedBidderQuo.NetAmount ?? 0);
                    prItem.NetAmount = (selectedBidderQuo.NetAmount ?? 0);

                    TotalPrice += prItem.Price * prItem.Qty;
                    Vat += prItem.VatAmount;
                    NetAmount += prItem.NetAmount;
                    DiscountTotal += prItem.DiscountTotal;
                } 
            }

            fields.Add("TotalPrice", TotalPrice.ToString("#,##0.00"));
            fields.Add("Vat", Vat.ToString("#,##0.00"));
            fields.Add("NetAmount", NetAmount.ToString("#,##0.00"));

            List<string> ActivityCodes = new List<string>();
            ProjectOperationService.IProjectOperationService projectService = new ProjectOperationService.ProjectOperationServiceClient();
            foreach (var prItemId in prItemIds)
            {
                PrePurchaseRequestItem ModelPrePurchaseRequestItem = null;
                if (null != (ModelPrePurchaseRequestItem = db.PrePurchaseRequestItems.FirstOrDefault(o => o.PrItemId == prItemId)))
                {
                    int ProjId =
                        ModelPrePurchaseRequestItem
                            .ProjectOperationExpense.ProjectExpense.Project.ProjId;
                    Decimal TotalAmount =
                        projectService.SelectProjectExpense(new ProjectExpense {ProjId = ProjId}, null)
                            .ToList()
                            .Sum(m => m.TotalAmount) ?? 0;
                    string StrBgmName =
                        ModelPrePurchaseRequestItem.ProjectOperationExpense.ProjectExpense.Project.Name;
                    string[] StrC = StrBgmName.Split(')');
                    string BgmName = StrC[0];
                    string BgmNo = StrC.Count() > 1 ? StrC[1] : "";
                    if (!string.IsNullOrWhiteSpace(BgmNo) && !ActivityCodes.Exists(o => o == BgmNo))
                    {
                        ActivityCodes.Add(BgmNo);
                    }
                }
            }
            fields.Add("ActivityCode", string.Join(", ", ActivityCodes.ToArray()));

            //var prItems = serviceItem.Select(new PurchaseRequestItem { PrId = id.Value },new[] {"MasBudgetExpense","PurchaseRequest","MasResourceItem"});
            //foreach (var prItem in prItems)
            //{
            //    if (prItem.HaveItem == true && prItem.MasResourceItem != null)
            //    {
            //        prItem.Descr = prItem.MasResourceItem.Name;
            //    }
            //}
            //DataTable modelItem = ConvertToDataTable(prItems);

            DataTable dtbSub = new DataTable();

            dtbSub.Columns.Add("Bidder");
            dtbSub.Columns.Add("Descr");
            dtbSub.Columns.Add("Qty");
            dtbSub.Columns.Add("Price");
            dtbSub.Columns.Add("VatAmount");
            dtbSub.Columns.Add("DiscountTotal");
            dtbSub.Columns.Add("Amount");

            foreach (var prItem in prItems)
            {
                dtbSub.Rows.Add(
                    prItem.BidderName,
                    prItem.ItemName,
                    prItem.Qty.ToString("#,##0"),
                    prItem.Price.ToString("#,##0.00"),
                    prItem.VatAmount.ToString("#,##0.00"),
                    prItem.DiscountTotal > 0 ? "ส่วนลด " + prItem.DiscountTotal.ToString("#,##0.00") + " บาท " : "",
                    prItem.NetAmount.ToString("#,##0.00"));
            }
            //foreach (DataRow r in modelItem.Rows)
            //{
            //    dtbSub.Rows.Add(r["Descr"].ToString(), 
            //        string.Format("{0}", r["Qty"]), 
            //        string.Format("{0:#,##0.00}", r["Price"]), 
            //        string.Format("{0:#,##0.00}", r["Amount"]));
            //}

            Table.Add("table1", dtbSub);

             //ส่วนดึงข้อมูลเจ้าหน้าที่ผู้ทำเอกสาร
            var userService = new UserService.UserServiceClient();
            var modelUser = userService.GetUsers().Where(o => o.EmpId == Class.GimsMembership.CurrentEmpId).FirstOrDefault();
            fields.Add("PersonName", string.Format("{0}",modelUser.FullName));            

            //ส่วนดึงข้อมูลหัวหน้างานตามสายบังคับบัญชาในระบบ
            var serviceUser = new EmployeeService.EmployeeServiceClient();
            var modelEmp = serviceUser.Select(new Employee { EmpId = Class.GimsMembership.CurrentEmpId }
                    , new[] { "Position.WorkingUpperPosition", "JobSite" }, true).FirstOrDefault();
            var upperPositionId = modelEmp.Position.WorkingUpperPosId;
            var modelEmpHead = serviceUser.Select(new Employee { PosId = upperPositionId, RecordStatus = "!D" }
                , new[] { "MasNamePrefix" }, true).FirstOrDefault(); //เพิ่ม new[]{"MasNamePrefix"} เพื่อให้ link ไม่ขาดจะได้ดึงคำนำหน้าชื่อมาด้วย
            fields.Add("HeadName", modelEmpHead.FullName);
            fields.Add("JobSiteName", modelEmp.JobSite.Name);

            //ส่วนดึงข้อมูลผู้อนุมัติ
            var serviceSysUser = new UserService.UserServiceClient();
            Employee modelSysUser = null; 
            try
            {
                modelSysUser = serviceSysUser.GetNameApproveTask(model.Code);
            }
            catch { }
            if (modelSysUser == null)
            {
                fields.Add("ApproveName", "                              ");
                fields.Add("PositionApproveName", "                              ");
            }
            else
            {
                var modelUserApprove = userService.GetUsers().Where(o => o.EmpId == modelSysUser.EmpId).FirstOrDefault();
                var Approve = modelUserApprove.FullName != null ? modelUserApprove.FullName : "";
                fields.Add("ApproveName", Approve);

                var modelPosition = userService.GetUsers().Where(o => o.EmpId == modelSysUser.EmpId).FirstOrDefault();
                var positionName = modelPosition.Employee != null && modelPosition.Employee.Position != null && modelPosition.Employee.Position.Name != null ? modelPosition.Employee.Position.Name : "";
                fields.Add("PositionApproveName", positionName);
            }

            //ส่วนดึงข้อมูลรายชื่อกรรมการตรวจรับ
            var serviceCommitteeGroup = new CommitteeGroupService.CommitteeGroupServiceClient();
            string[] _committeeIncludeSubclass = new[]
            {
                "Committees.CommitteeType", "Committees.CommitteePosition", "Committees.CommitteeFunction", "Committees.Employee.Position"
            };

            var ModelCommittee = (serviceCommitteeGroup.Select(new CommitteeGroup
            {
                CommitteeGroupId = model.CommitteeGroupId.Value
            }, _committeeIncludeSubclass).First().Committees ?? new List<Committee>()).Where(o => o.RecordStatus != "D");

            // Grouping committee
            List<CommitteeWithEmployee> committeeWithEmployees = new List<CommitteeWithEmployee>();
            if (ModelCommittee != null)
            {
                var group = ModelCommittee.GroupBy(x => x.ComFunctionId).ToList(); 
                for (int i = 0; i < group.Count(); i++)
                {
                    for (int j = 0; j < group[i].Count(); j++)  { 
                        Committee committee1 = group[i].ElementAt(j);
                        if (committee1.EmpId.HasValue)
                        {

                            var criteriaEmp = new Employee { EmpId = committee1.EmpId.Value };
                            var includeDefault = new[] {"Position.JobSite", "MasNamePrefix"};
                            var tempModel = serviceUser.Select(criteriaEmp, includeDefault, true).FirstOrDefault();
                            committeeWithEmployees.Add(new CommitteeWithEmployee
                            {
                                Committee = committee1,
                                Employee = tempModel
                            });
                        }
                    }                   
                }
            }

            // order by committee function
            List<Dictionary<string, string>> ListCommittee = new List<Dictionary<string, string>>();
            foreach (var committeeWithEmployee in committeeWithEmployees.OrderBy(o=>o.Committee.ComPositionId))
            {
                Dictionary<string, string> dics = new Dictionary<string, string>();
                dics.Add("empname", committeeWithEmployee.Employee.FullName);
                dics.Add("posname", committeeWithEmployee.Employee.Position.Name);
                dics.Add("compos", committeeWithEmployee.Committee.CommitteePosition.LookUpName);
                ListCommittee.Add(dics); 
            }


            string strTemplatePath = Server.MapPath("~/Templates/แบบฟอร์มขอซื้อ_ขอจ้าง.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("แบบฟอร์มขอซื้อ_ขอจ้าง{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            //ReportPRTable(strTemplatePath, dtbSub.Rows.Count, ListCommittee.Count, strSaveAsPath + strSaveAsFileName);
            CreatePRTable(strTemplatePath, dtbSub.Rows.Count, strSaveAsPath + strSaveAsFileName, DiscountTotal, ListCommittee.Count);//, 0);
            if (mailMerge.MergeTemplate(strSaveAsPath + strSaveAsFileName, strSaveAsPath + strSaveAsFileName, fields, Table, ListCommittee, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                if (true)
                {
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                }
                Response.End();
            } 
        }

        private class CommitteeWithEmployee
        {
            public Committee Committee { get; set; }
            public Employee Employee { get; set; }
        }
        private string GetRequireDate(PurchaseRequest model)
        {
            var LookUpService = new KPIS.GERP.WEB.GIMS.IcmMasLookUpService.IcmMasLookUpServiceClient();
            var durCountSelectList = LookUpService.MasLookUpSelectList(KPIS.GERP.Models.ICM.IcmMasLookUpType.LookUpType.DurationCount);
            var durCountSelectListItem = durCountSelectList.FirstOrDefault(o => o.Value == (model != null ? Convert.ToString(model.DurCountId) : ""));
            var durCountWording = durCountSelectListItem == null ? string.Empty : durCountSelectListItem.Text;

            string result = "";
            result += model.RequireDate;

            if (model.DurTypeId == 10)
            {
                var task = new GERPContext()
                    .Tasks
                    .Include("ApproveProcess")
                    .OrderByDescending(o => o.TaskId)
                    .FirstOrDefault(o => o.RefId == model.PrId && o.ApproveProcess.AppPrcGrpId == 8);
                result += model.RequireDuration + " วัน นับจาก " + @durCountWording;


                if (model.DurCountId == 10) //วันที่สร้างรายการ
                {
                    if (model.CreatedWhen.HasValue)
                    {
                        result += " (วันที่สร้างรายการ คือ " + model.CreatedWhen.Value.ToString("dd MMM yyyy") + ") ";
                    }
                }
                else if (model.DurCountId == 11) // วันที่ยืนยันรายการ - ส่งขออนุมัติรายการ
                {
                    if (task != null && task.CreatedWhen.HasValue)
                    {
                        result += " (วันที่ยืนยันรายการ คือ " + task.CreatedWhen.Value.ToString("dd MMM yyyy") + ") ";
                    }
                }
                else if (model.DurCountId == 12) // วันที่อนุมัติรายการ
                {
                    if (task != null && task.ApprovedWhen.HasValue)
                    {
                        result += " (วันที่อนุมัติรายการ คือ " + task.ApprovedWhen.Value.ToString("dd MMM yyyy") + ") " + ") ";
                    }
                }
                result += " ";
            }
            else
            {
                result += " วันที่ " +
                          (model.RequireDate != null ? model.RequireDate.Value.ToString("dd MMM yyyy") : "");
            }
            return result;
        }

        public void CreatePRTable(string strTemplateFilePath, int row, string saveTemp, decimal discountTotal, int committeeCount)//, decimal extraDiscount)
        {
            using (DocX document = DocX.Load(strTemplateFilePath))
            {
                if (document.Tables[1].ColumnCount >= 5)
                {
                    //วนลูปรายการในตาราง
                    for (int i = 0; i < row; i++)
                    {
                        Row rx = document.Tables[1].InsertRow(document.Tables[1].RowCount);

                        rx.Cells[0].Paragraphs[0].Append("«" + "Bidder" + (i + 1).ToString() + "»");
                        rx.Cells[0].Paragraphs[0].Alignment = Alignment.left;
                        rx.Cells[0].Paragraphs[0].FontSize(14);
                        rx.Cells[0].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                        rx.Cells[1].Paragraphs[0].Append("«" + "Descr" + (i + 1).ToString() + "»");
                        rx.Cells[1].Paragraphs[0].Alignment = Alignment.left;
                        rx.Cells[1].Paragraphs[0].FontSize(14);
                        rx.Cells[1].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                        rx.Cells[2].Paragraphs[0].Append("«" + "Qty" + (i + 1).ToString() + "»");
                        rx.Cells[2].Paragraphs[0].Alignment = Alignment.center;
                        rx.Cells[2].Paragraphs[0].FontSize(14);
                        rx.Cells[2].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                        rx.Cells[3].Paragraphs[0].Append("«" + "Price" + (i + 1).ToString() + "»");
                        rx.Cells[3].Paragraphs[0].Alignment = Alignment.right;
                        rx.Cells[3].Paragraphs[0].FontSize(14);
                        rx.Cells[3].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                        rx.Cells[4].Paragraphs[0].Append("«" + "Amount" + (i + 1).ToString() + "»");
                        rx.Cells[4].Paragraphs[0].Alignment = Alignment.right;
                        rx.Cells[4].Paragraphs[0].FontSize(14);
                        rx.Cells[4].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    }

                    //บรรทัดยอดรวมในตาราง
                    Row total = document.Tables[1].InsertRow(document.Tables[1].RowCount);
                    total.MergeCells(0, 2);
                    //หลังการเมิจภายในฟิลด์จะเกิดช่องว่างหากใส่ข้อมูลเลยจะทำให้ช่องกว้างกว่าปกติ จึงต้องทำการเคีลยร์ก่อน
                    int paraCount3 = total.Cells[0].Paragraphs.Count;

                    for (int k = 1; k < paraCount3; k++)
                    {
                        total.Cells[0].Paragraphs[0].Remove(false);
                    }
                    total.Cells[1].Paragraphs[0].Append("เป็นเงิน");
                    total.Cells[1].Paragraphs[0].Alignment = Alignment.right;
                    total.Cells[1].Paragraphs[0].FontSize(14);
                    total.Cells[1].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    total.Cells[2].Paragraphs[0].Append("«" + "TotalPrice" + "»");
                    total.Cells[2].Paragraphs[0].Alignment = Alignment.right;
                    total.Cells[2].Paragraphs[0].FontSize(14);
                    total.Cells[2].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));

                    //บรรทัดภาษีมูลค่าเพิ่มในตาราง
                    Row vat = document.Tables[1].InsertRow(document.Tables[1].RowCount);
                    vat.MergeCells(0, 2);
                    //หลังการเมิจภายในฟิลด์จะเกิดช่องว่างหากใส่ข้อมูลเลยจะทำให้ช่องกว้างกว่าปกติ จึงต้องทำการเคีลยร์ก่อน
                    int paraCount2 = vat.Cells[0].Paragraphs.Count;

                    for (int k = 1; k < paraCount2; k++)
                    {
                        vat.Cells[0].Paragraphs[0].Remove(false);
                    }
                    vat.Cells[1].Paragraphs[0].Append("VAT 7%");
                    vat.Cells[1].Paragraphs[0].Alignment = Alignment.right;
                    vat.Cells[1].Paragraphs[0].FontSize(14);
                    vat.Cells[1].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    vat.Cells[2].Paragraphs[0].Append("«" + "Vat" + "»");
                    vat.Cells[2].Paragraphs[0].Alignment = Alignment.right;
                    vat.Cells[2].Paragraphs[0].FontSize(14);
                    vat.Cells[2].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));

                    if (discountTotal > 0)
                    {
                        //บรรทัดส่วนลด%
                        Row dP = document.Tables[1].InsertRow(document.Tables[1].RowCount);
                        dP.Cells[3].Paragraphs[0].Append("ส่วนลด %");
                        dP.Cells[3].Paragraphs[0].Alignment = Alignment.right;
                        dP.Cells[3].Paragraphs[0].FontSize(14);
                        dP.Cells[3].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                        dP.Cells[4].Paragraphs[0].Append("«" + "DiscountPercent" + "»");
                        dP.Cells[4].Paragraphs[0].Alignment = Alignment.right;
                        dP.Cells[4].Paragraphs[0].FontSize(14);
                        dP.Cells[4].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    }

                    //if (extraDiscount > 0)
                    //{
                    //    //บรรทัดส่วนลดพิเศษ
                    //    Row dS = document.Tables[1].InsertRow(document.Tables[1].RowCount);
                    //    dS.Cells[3].Paragraphs[0].Append("ส่วนลดพิเศษ");
                    //    dS.Cells[3].Paragraphs[0].Alignment = Alignment.center;
                    //    dS.Cells[3].Paragraphs[0].FontSize(14);
                    //    dS.Cells[3].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    //    dS.Cells[4].Paragraphs[0].Append("«" + "ExtraDiscount" + "»");
                    //    dS.Cells[4].Paragraphs[0].Alignment = Alignment.center;
                    //    dS.Cells[4].Paragraphs[0].FontSize(14);
                    //    dS.Cells[4].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    //}

                    //บรรทัดยอดเงินรวมท้ายตาราง
                    Row sum = document.Tables[1].InsertRow(document.Tables[1].RowCount);
                    sum.MergeCells(0, 2);
                    //หลังการเมิจภายในฟิลด์จะเกิดช่องว่างหากใส่ข้อมูลเลยจะทำให้ช่องกว้างกว่าปกติ จึงต้องทำการเคีลยร์ก่อน
                    int paraCount1 = sum.Cells[0].Paragraphs.Count;

                    for (int k = 1; k < paraCount1; k++)
                    {
                        sum.Cells[0].Paragraphs[0].Remove(false);
                    }

                    sum.Cells[0].Paragraphs[0].Append("«" + "ThaiBaht" + "»");
                    sum.Cells[0].Paragraphs[0].Alignment = Alignment.right;
                    sum.Cells[0].Paragraphs[0].FontSize(14);
                    sum.Cells[0].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    sum.Cells[1].Paragraphs[0].Append("รวมเป็นเงิน");
                    sum.Cells[1].Paragraphs[0].Alignment = Alignment.right;
                    sum.Cells[1].Paragraphs[0].FontSize(14);
                    sum.Cells[1].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    sum.Cells[2].Paragraphs[0].Append("«" + "NetAmount" + "»");
                    sum.Cells[2].Paragraphs[0].Alignment = Alignment.right;
                    sum.Cells[2].Paragraphs[0].FontSize(14);
                    sum.Cells[2].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));

                    
                    for (int j = 0; j < committeeCount; j++)
                    {
                        Row rxCommit = document.Tables[3].InsertRow(document.Tables[3].RowCount - 1);

                        rxCommit.Cells[0].Paragraphs[0].Append(string.Format("5.{0} «empname{0}»", (j + 1)));
                        rxCommit.Cells[0].Paragraphs[0].Alignment = Alignment.left;
                        rxCommit.Cells[0].Paragraphs[0].FontSize(15);

                        rxCommit.Cells[1].Paragraphs[0].Append(string.Format("ตำแหน่ง «posname{0}»", (j + 1)));
                        rxCommit.Cells[1].Paragraphs[0].Alignment = Alignment.left;
                        rxCommit.Cells[1].Paragraphs[0].FontSize(15);

                        rxCommit.Cells[2].Paragraphs[0].Append(string.Format("«compos{0}»", (j + 1)));
                        rxCommit.Cells[2].Paragraphs[0].Alignment = Alignment.left;
                        rxCommit.Cells[2].Paragraphs[0].FontSize(15);

                        //rxCommit.Cells[0].Paragraphs[0].Append(string.Format("\t\t {1} \n\t\t      ตำแหน่ง {2}", j + 1
                        //                                                    , "«" + "empname" + (j + 1).ToString() + "»"
                        //                                                    , "«" + "posname" + (j + 1).ToString() + "»"));
                        //var font = new FontFamily("TH SarabunPSK");
                        //rxCommit.Cells[0].Paragraphs[0].FontSize(15);
                        //rxCommit.Cells[0].Paragraphs[0].Font(font);
                        //rxCommit.Cells[1].Paragraphs[0].Append("«" + "compos" + (j + 1).ToString() + "»");
                        //rxCommit.Cells[1].Paragraphs[0].Alignment = Alignment.right;
                        //rxCommit.Cells[1].Paragraphs[0].FontSize(15);
                        //rxCommit.Cells[1].Paragraphs[0].Font(font);
                    }
                    document.SaveAs(saveTemp);
                }
            }
        }


        public void ReportPRTable(string strTemplateFilePath, int rowItem, int rowCommit,string saveTemp)
        {
            using (DocX document = DocX.Load(strTemplateFilePath))
            {
                var font = new FontFamily("TH SarabunPSK");
                for (int i = 0; i < rowItem; i++)
                {                    
                    Row rxItem = document.Tables[1].InsertRow(document.Tables[1].RowCount-1);

                    var format =
                        string.Format(
                            "\t\t\t2.1.{0} {1} จำนวน {2} หน่วย ราคาหน่วยละ {3} บาท ภาษี {4} บาท {5}รวมเป็นเงินทั้งสิ้น {6} บาท "
                            , i + 1,
                            "«" + "Descr" + (i + 1).ToString() + "»",
                            "«" + "Qty" + (i + 1).ToString() + "»",
                            "«" + "Price" + (i + 1).ToString() + "»", 
                            "«" + "VatAmount" + (i + 1).ToString() + "»",
                            "«" + "DiscountTotal" + (i + 1).ToString() + "»",
                            "«" + "Amount" + (i + 1).ToString() + "»");

                    rxItem.Cells[0].Paragraphs[0].Append(format);                   
                    
                    rxItem.Cells[0].Paragraphs[0].FontSize(15);
                    rxItem.Cells[0].Paragraphs[0].Font(font);
                }

                for (int j = 0; j < rowCommit; j++)
                {
                    Row rxCommit = document.Tables[2].InsertRow(document.Tables[2].RowCount - 1);

                    rxCommit.Cells[0].Paragraphs[0].Append(string.Format("\t\t {1} \n\t\t      ตำแหน่ง {2}", j + 1
                                                                        , "«" + "empname" + (j + 1).ToString() + "»"
                                                                        , "«" + "posname" + (j + 1).ToString() + "»"));
                    rxCommit.Cells[0].Paragraphs[0].FontSize(15);
                    rxCommit.Cells[0].Paragraphs[0].Font(font);
                    rxCommit.Cells[1].Paragraphs[0].Append("«" + "compos" + (j + 1).ToString() + "»");
                    rxCommit.Cells[1].Paragraphs[0].Alignment = Alignment.right;
                    rxCommit.Cells[1].Paragraphs[0].FontSize(15);
                    rxCommit.Cells[1].Paragraphs[0].Font(font);
                }

                document.SaveAs(saveTemp);
            }
        }

        public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            System.ComponentModel.PropertyDescriptorCollection properties =
                 System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

        //public void ToGateway(int id)
        //{
        //    var service = new PurchaseRequestService.PurchaseRequestServiceClient();
        //    var PrInfo = service.Select(new PurchaseRequest { PrId = id }, null).FirstOrDefault();

        //    //Class.CreateRequest createRequest = new Class.CreateRequest()
        //    //    {
        //    //        ref_type = PrInfo.Code,
        //    //        supplier_tax_code = ,
        //    //        supplier_branch_code = ,
        //    //        date = ,
        //    //        announce_code = ,
        //    //        g_office_code = ,
        //    //        g_office_name = ,
        //    //        remark_1 = ,
        //    //        remark_2 = ,
        //    //        remark_3 = ,
        //    //        contact_code = ,
        //    //        contact_name = ,
        //    //        project_code = ,
        //    //        project_name = ,
        //    //        valid_datevdelivery_date = ,
        //    //        tel = ,
        //    //        doc_id = ,
        //    //    };
        //}
    }
}